package org.iabako.server.serviceimpl.business;

import org.iabako.server.dao.business.QueryDefinitionDAO;
import org.iabako.shared.iservice.generic.EnMasseService;
import org.iabako.shared.querydefinition.columndefinition.ClientColumnEnum;
import org.iabako.shared.querydefinition.columndefinition.ColumnDefinition;
import org.iabako.shared.querydefinition.dto.QueryDefinitionDTO;
import org.iabako.shared.querydefinition.dto.QueryResultDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * Created by jose on 07/03/15.
 */
public abstract class AbstractEnMasseService implements EnMasseService{

    @Autowired
    QueryDefinitionDAO queryDefinitionDAO;

    public String prepareEnMasseAction(QueryDefinitionDTO queryDefinitionDTO) {

        for (ColumnDefinition columnDefinition : queryDefinitionDTO.getSelectColumns()) {
            if (columnDefinition != ClientColumnEnum.clientId
                    && columnDefinition != ClientColumnEnum.name
                    && columnDefinition != ClientColumnEnum.email) {

                queryDefinitionDTO.addColumnExclusion(columnDefinition);
            }
        }

        queryDefinitionDTO.setPageSize(-1);

        queryDefinitionDAO.executeQueryDefinition(queryDefinitionDTO);
        Map<Long, QueryResultDTO> results = queryDefinitionDTO.getResults();

        HttpSession session = (((ServletRequestAttributes) RequestContextHolder.
                currentRequestAttributes()).getRequest()).getSession();

        String tokenSession = new Date().getTime() + "";

        session.setAttribute(tokenSession, results);

        return tokenSession;
    }

    public Map<Long, QueryResultDTO> getClients(String clientsCommunicationsSessionToken) {
        HttpSession session = (((ServletRequestAttributes) RequestContextHolder.
                currentRequestAttributes()).getRequest()).getSession();

        Map<Long, QueryResultDTO> clients = (Map<Long, QueryResultDTO>) session.getAttribute(clientsCommunicationsSessionToken);

        session.removeAttribute(clientsCommunicationsSessionToken);

        return clients;
    }
}
